#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
语音助手演示程序
展示完整的语音转文本到文本转回答流程
"""

import os
import logging
from voice_assistant import VoiceAssistant

logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)


def demo_audio_processing():
    """演示音频处理功能"""
    print("=== 音频处理演示 ===")
    
    # 创建语音助手实例
    assistant = VoiceAssistant()
    
    # 检查测试音频文件
    audio_file = "test_1.pcm"
    if not os.path.exists(audio_file):
        print(f"测试音频文件 {audio_file} 不存在")
        print("请确保有PCM格式的音频文件用于测试")
        return
    
    # 获取音频文件信息
    print("【音频文件信息】")
    audio_info = assistant.get_audio_info(audio_file)
    print(f"文件: {audio_info['file_path']}")
    print(f"大小: {audio_info['file_size']} 字节")
    print(f"时长: {audio_info['estimated_duration_sec']:.2f} 秒")
    
    # 处理音频文件
    print(f"\n【开始处理音频文件】")
    print("=" * 50)
    
    try:
        transcribed_text, ai_response = assistant.process_audio_file(
            audio_file_path=audio_file,
            stream=False,  # 非流式输出，便于演示
            enable_web_search=False
        )
        
        print(f"\n【转写结果】")
        print(f"用户: {transcribed_text}")
        
        print(f"\n【AI回答】")
        print(f"助手: {ai_response}")
        
    except Exception as e:
        print(f"处理失败: {e}")


def demo_text_conversation():
    """演示文本对话功能"""
    print("\n=== 文本对话演示 ===")
    
    # 创建语音助手实例
    assistant = VoiceAssistant()
    
    # 测试对话
    test_questions = [
        "你好，请介绍一下你自己",
        "请解释一下什么是机器学习",
        "推荐一本编程书籍"
    ]
    
    for i, question in enumerate(test_questions, 1):
        print(f"\n【对话 {i}】")
        print(f"用户: {question}")
        print("助手: ", end="")
        
        try:
            response = assistant.process_text_directly(question, stream=False)
            print(response)
        except Exception as e:
            print(f"错误: {e}")
    
    # 显示对话历史
    print(f"\n【对话历史】")
    history = assistant.get_conversation_history()
    for i, msg in enumerate(history):
        role = "用户" if msg["role"] == "user" else "助手"
        content = msg["content"][:50] + "..." if len(msg["content"]) > 50 else msg["content"]
        print(f"{i+1}. {role}: {content}")


def demo_streaming():
    """演示流式输出功能"""
    print("\n=== 流式输出演示 ===")
    
    # 创建语音助手实例
    assistant = VoiceAssistant()
    
    question = "请用一句话总结Python编程语言的特点"
    print(f"用户: {question}")
    print("助手: ", end="")
    
    try:
        # 流式输出
        assistant.process_text_directly(question, stream=True)
        print("\n")
    except Exception as e:
        print(f"错误: {e}")


def main():
    """主演示函数"""
    print("=== 语音助手集成服务演示 ===")
    print("本演示将展示以下功能：")
    print("1. 音频文件处理（语音转文本 + 文本转回答）")
    print("2. 直接文本对话")
    print("3. 流式输出演示")
    print("4. 对话历史管理")
    print()
    
    try:
        # 演示音频处理
        demo_audio_processing()
        
        # 演示文本对话
        demo_text_conversation()
        
        # 演示流式输出
        demo_streaming()
        
        print("\n=== 演示完成 ===")
        print("语音助手集成服务已成功运行！")
        print("现在你可以使用 voice_assistant.py 进行交互式操作。")
        
    except Exception as e:
        print(f"演示过程中出现错误: {e}")
        logger.error(f"演示失败: {e}")


if __name__ == "__main__":
    main()
